package name.vaccari.matteo.tai.chat.servlet;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;

import name.vaccari.matteo.tai.chat.domain.Message;
import name.vaccari.matteo.tai.chat.servlet.ChatController;
import name.vaccari.matteo.tai.chat.util.FakeRepository;
import name.vaccari.matteo.tai.chat.views.ChatView;

import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;



public class ChatControllerTest {

	private FakeRepository fakeRepository;
	private PrintWriter writer;
	private ByteArrayOutputStream stream;
	private ChatView chatView;
	
	@Before
	public void setUp() throws Exception {
		fakeRepository = new FakeRepository();
		stream = new ByteArrayOutputStream();
		writer = new PrintWriter(stream);
		chatView = new ChatView();
	}

	@Test
	public void getTest() throws Exception {
		fakeRepository.save(new Message("primo", "pippo"));
		fakeRepository.save(new Message("secondo", "pippo"));
		ChatController controller = new ChatController(fakeRepository, chatView);
		
		controller.service("GET", null, writer);
		
		assertEquals("<ul><li>secondo</li><li>primo</li></ul>", stream.toString());
	}
	
	@Test
	public void postTest() throws Exception {
		ChatController controller = new ChatController(fakeRepository, chatView);
		String messageText = "messaggio";
		String author = "pippo";
		controller.service("POST", new Message(messageText, author), writer);
		
		assertEquals(1, fakeRepository.messageCount());
		assertEquals(messageText, fakeRepository.getMessage(0));
		assertEquals("<ul><li>" + author + ": " + messageText + "</li></ul>", stream.toString());
	}
	
	@Test
	public void testRepositoryShouldReturnXMessages() throws Exception {
		ChatController controller = new ChatController(fakeRepository,chatView);
		controller.service("POST", new Message("pippo", "pippo"), writer);
		assertEquals(5, fakeRepository.howMany());
	}
}
